package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.adapter.MusicItemAdapter;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.viewTools.ViewAlphaAnimation;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MusicListActivity extends BaseActivity {
    private static final String TAG = "MusicListActivity";
    private MusicListType mMusicListType = MusicListType.TYPE_LOCAL;
    private CardView mBackToTopButton;
    private ListView mListViewMusicList;
    private MusicItemAdapter mAdapter;
    private List<MusicInfo> mMusicList;
    private ViewAlphaAnimation mViewAlphaAnimation;
    private MusicService.MusicBinder mMusicBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        if ((mMusicBinder = getMusicServiceBinder()) == null) {
            finish();
        }
        WindowTools.statusBarLightMode(getWindow());

        initView();
        addListener();
        setToolbar();
        //show music playing info tab
        setEnableMusicTabView(true);
        setEnableMusicListener(true);
        registerMusicListener(mMusicBinder);
        initListView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MusicSearchActivity.RESULT_CODE && data != null) {
            if (data.getBooleanExtra(MusicSearchActivity.NEED_LOCATE, false)) {
                int locateId = data.getIntExtra(MusicSearchActivity.LOCATE_ID, -1);
                for (int i = 0; i < mMusicList.size(); i++) {
                    if (mMusicList.get(i).getId() == locateId && mListViewMusicList != null) {
                        mListViewMusicList.smoothScrollToPositionFromTop(i, 0, 300);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.d(TAG, "onBackPressed(): ");
        setPendingTransition(R.anim.fake_anim, R.anim.music_list_activity_exit);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            Log.d(TAG, "onOptionsItemSelected(): item id is android.R.id.home");
            finish();
            setPendingTransition(R.anim.fake_anim, R.anim.music_list_activity_exit);
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        Log.d(TAG, "initView(): ");
        Toolbar toolbarMusicList = findViewById(R.id.toolbar_music_list);
        setSupportActionBar(toolbarMusicList);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        mListViewMusicList = findViewById(R.id.listview_music_list);
        mBackToTopButton = findViewById(R.id.button_back_to_top);

        mViewAlphaAnimation = new ViewAlphaAnimation();
    }

    //更新列表activity的actionbar的文本
    private void updateMusicListTitle() {
        Log.d(TAG, "updateMusicListTitle(): update the music counts");
        int numOfMusic = 0;
        if (mMusicList != null)
            numOfMusic = mMusicList.size();
        String text;
        if (mMusicListType == MusicListType.TYPE_FAVORITE) {
            text = "我喜欢(" + numOfMusic + "首)";
        } else {
            text = "本地歌曲(" + numOfMusic + "首)";
        }
        ((TextView) findViewById(R.id.textview_music_list_title)).setText(text);
        if (numOfMusic == 0) {
            findViewById(R.id.activity_music_list_listview_container).setVisibility(View.GONE);
        } else {
            findViewById(R.id.activity_music_list_listview_container).setVisibility(View.VISIBLE);
        }
    }

    private void addListener() {
        findViewById(R.id.search_music).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MusicListActivity.this, MusicSearchActivity.class);
                intent.putExtra(MusicSearchActivity.TYPE, mMusicListType.toString());
                jumpToActivity(intent);
            }
        });
        findViewById(R.id.imageview_music_list_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.makeToast("这是分享歌曲的功能");
            }
        });
        //返回顶端按钮的监听事件
        mBackToTopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick(): back to music list top");
                mListViewMusicList.smoothScrollToPositionFromTop(0, 0, 300);
            }
        });
        mListViewMusicList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= MusicPlayerSettings.getBackToTopButtonAppear() && mBackToTopButton != null) {
                    Log.d(TAG, "onScroll(): the back to top button appears");
                    mViewAlphaAnimation.appear(mBackToTopButton);
                } else if (mBackToTopButton != null) {
                    Log.d(TAG, "onScroll(): the back to top button disappears");
                    mViewAlphaAnimation.disappear(mBackToTopButton);
                }
            }
        });
    }

    //设置工具栏标题和初始化列表类型
    private void setToolbar() {
        Log.d(TAG, "setToolbar(): update the action bar info");
        Intent intent = getIntent();
        MusicListType type = (MusicListType) intent.getSerializableExtra("musicListType");
        if (type != null) {
            mMusicListType = type;
            updateMusicListTitle();
        }
    }

    //根据展示列表的类型来初始化listview
    private void initListView() {
        Log.d(TAG, "initListView(): start to init listView");
        mMusicList = new ArrayList<MusicInfo>();
        if (mMusicListType == MusicListType.TYPE_FAVORITE) {
            mMusicList = MusicInfo.getFavoriteMusic();
        } else {
            mMusicList = MusicInfo.getLocalMusic();
        }
        updateMusicListTitle();
        mAdapter = new MusicItemAdapter(this, mMusicList, mMusicBinder, mMusicListType == MusicListType.TYPE_FAVORITE ?
                MusicItemAdapter.MODE_FAVORITE : MusicItemAdapter.MODE_NORMAL);
        mListViewMusicList.setAdapter(mAdapter);
        mListViewMusicList.setEmptyView(findViewById(R.id.music_list_empty));
        mListViewMusicList.addFooterView(
                LayoutInflater.from(this).inflate(R.layout.normal_footer_view, mListViewMusicList, false)
                , null, false
        );
        mListViewMusicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MusicInfo music = (MusicInfo) mAdapter.getItem(position);
                if (music != null)
                    Log.d(TAG, "onItemClick(): change music and playing " + music.getTitle());
                else
                    Log.d(TAG, "onItemClick(): the changed music is null");
                if (mMusicBinder != null && music != null) {
                    if (music.getId() != mMusicBinder.getId() || mMusicBinder.getMusicListType() != mMusicListType) {
                        mMusicBinder.start(mMusicListType, null, music);
                    } else if (!mMusicBinder.isPlaying()) {
                        mMusicBinder.start();
                    }
                    if (MusicPlayerSettings.isAutoIntoPlayScreen()) {
                        jumpToMusicPlayActivity();
                    }
                }
            }
        });
        mAdapter.setOnMusicDeleteListener(musicInfo -> {
            if (musicInfo != null && mMusicBinder != null) {
                mMusicList.remove(musicInfo);
                mMusicBinder.changeMusicFavorite(musicInfo);
                updateMusicListTitle();
                mAdapter.setMusicList(mMusicList);
            }
        });
        mAdapter.setOnMoreFeaturesListener(new MusicItemAdapter.OnMoreFeaturesListener() {
            @Override
            public void onExpandMoreFeatures(MusicInfo musicInfo) {
                ToastUtil.makeToast("本地歌曲列表，展开更多功能");
            }

            @Override
            public void onRequestMusicVideo(MusicInfo musicInfo) {
                ToastUtil.makeToast("播放歌曲MV功能");
            }
        });
    }

    private void jumpToActivity(Intent intent) {
        startActivityForResult(intent, 1);
        setPendingTransition(R.anim.activity_vertical_enter, R.anim.fake_anim);
    }

    @Override
    protected void onMusicPrepared(MusicInfo musicInfo) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onMusicEmpty(MusicInfo musicInfo) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }
}